from typing import List, Dict, Any, Optional
from .catalog_manager import CatalogManager, TableInfo
from .storage_engine import StorageEngine

class Executor:
    def __init__(self, catalog_manager: CatalogManager, storage_engine: StorageEngine):
        self.catalog_manager = catalog_manager
        self.storage_engine = storage_engine
    
    def execute_create_table(self, table_info: TableInfo) -> bool:
        """执行创建表操作"""
        return self.catalog_manager.create_table(table_info)
    
    def execute_insert(self, table_name: str, values: List[Any]) -> bool:
        """执行插入操作"""
        table_info = self.catalog_manager.get_table(table_name)
        if not table_info:
            raise Exception(f"Table {table_name} does not exist")
        
        if len(values) != len(table_info.columns):
            raise Exception(f"Column count doesn't match value count")
        
        # 构建记录字典
        record = {}
        for i, column in enumerate(table_info.columns):
            record[column.name] = values[i]
        
        return self.storage_engine.insert_record(table_info, record)
    
    def execute_select(self, table_name: str, 
                      columns: Optional[List[str]] = None,
                      condition_func=None) -> List[Dict[str, Any]]:
        """执行查询操作"""
        table_info = self.catalog_manager.get_table(table_name)
        if not table_info:
            raise Exception(f"Table {table_name} does not exist")
        
        # 获取所有记录
        records = self.storage_engine.get_all_records(table_info)
        
        # 应用条件过滤
        if condition_func:
            records = [record for record in records if condition_func(record)]
        
        # 选择指定列
        if columns and columns != ["*"]:
            filtered_records = []
            for record in records:
                filtered_record = {col: record[col] for col in columns if col in record}
                filtered_records.append(filtered_record)
            records = filtered_records
        
        return records
    
    def execute_delete(self, table_name: str, condition_func=None) -> int:
        """执行删除操作"""
        table_info = self.catalog_manager.get_table(table_name)
        if not table_info:
            raise Exception(f"Table {table_name} does not exist")
        
        # 如果没有条件，删除所有记录
        if condition_func is None:
            condition_func = lambda record: True
        
        return self.storage_engine.delete_records(table_info, condition_func)